package com.nj.dms.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nj.dms.bean.Essay;
import com.nj.dms.dao.EssayDao;
import com.nj.dms.dao.impl.EssayDaoImpl;

/**
 * 增加文章
 */
@WebServlet("/AddEssay")
public class AddEssay extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 获取用户数据
		String title = request.getParameter("title").trim();
		String version = request.getParameter("version").trim();
		int thick = new Integer(request.getParameter("thick").trim());
		String digest = request.getParameter("digest").trim();
		String content = request.getParameter("content").trim();

		// 检查数据合法性
		// 设置检查的标记，默认是通过
		boolean flag = true;

		// 检查标题
		if (title == null || "".equals(title)) {

			flag = false;
			request.setAttribute("titleErr", "标题不能为空");

		}

		// 检查密级1~4
		if (thick < 1 || thick > 4) {

			flag = false;
			request.setAttribute("thickErr", "请重新选择密级");

		}

		if (flag) {

			// 将数据保存到bean
			// 审核：如果密级为1（个人），就不需要审核，将值设置为1（通过），否则设置为0（需要审核）
			int audit = thick == 1 ? 1 : 0;
			String userName = (String) request.getSession().getAttribute("userName");

			System.out.println(userName);

			Date date = new Date();
			Essay essay = new Essay(userName, title, digest, content, version, thick, audit, date, date);

			// 将数据保存到数据库
			EssayDao essayDao = new EssayDaoImpl();

			if (essayDao.addEssay(essay)) {

				// 保存数据到数据库成功

				response.sendRedirect("document/add-document-menu.jsp");

			} else {
				// 保存到数据库失败

				// 保存用户数据
				request.setAttribute("title", title);
				request.setAttribute("version", version);
				request.setAttribute("thick", thick);
				request.setAttribute("digest", digest);
				request.setAttribute("content", content);

				request.getRequestDispatcher("document/add-essay.jsp").forward(request, response);

			}

		} else {

			// 数据不合法，保存用户数据，执行服务器端跳转

			// 保存用户数据
			request.setAttribute("title", title);
			request.setAttribute("version", version);
			request.setAttribute("thick", thick);
			request.setAttribute("digest", digest);
			request.setAttribute("content", content);

			request.getRequestDispatcher("document/add-essay.jsp").forward(request, response);

		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
